<template>
  <div class="ocr-table-html">
    <div
      id="cell_result" 
      ref="resultTable" 
      v-html="tableHtmlS"
      :key="timeKey"
    ></div>
  </div>
</template>

<script>
import activeShowMixin from "../../mixin/activeShow.mixin";
import $ from 'jquery';

export default {
  name: 'ocrTable',
  mixins: [activeShowMixin], // 组件插件 可插入方法（全局方法或生命周期方法） 
  props: {
    tableHtml: {
        type: String,
        default: '',
    },
    doResultId: {
        type: String,
        default: '',
    },
    selectionSwitchChange: {
        type: Function,
        default: function () {
            return false;
        },
    },
    auxPositionChange: {
        type: Function,
        default: function () {
            return false;
        },
    },
    // 是否展示表格
    showOcrTable: {
        type: Boolean,
        default: false,
    },
  },
  data() {
        return {
          tableHtmlS: '', // props 存储
          timeKey: '',
          oldDom: '', // 编辑之前的dom结构
          oldValue: '', // 编辑之前的value值
          newValue: '', // 编辑之后的value值
          clickId: '', // 当前点击的id
          isedit: false, // 是否还在编辑、刚退出编辑的变化过程中。
        }
  },
  mounted() {

    // 解决页面全选持续问题
    if(window.getSelection() && this.$refs.resultTable ){
        this.$refs.resultTable.focus() //解决ff不获取焦点无法定位问题
        var range = window.getSelection();//创建range
        range.selectAllChildren(this.$refs.resultTable);//range 选择obj下所有子内容
        range.selectAllChildren(this.$refs.resultTable) && range.collapseToEnd();
    }

  },
  beforeUpdate() {

    if( $("#cell_result") && this.showOcrTable ){

      // 首次点击光标无法定位
      if( this.fileEdit === 1 ){
        console.log( 'table fileEdit', this.fileEdit, $("#cell_result"), $("#cell_result").find('td :last').eq(0) );
        
        setTimeout(() => {
          $("#cell_result").find('td').eq(0).click();
        }, 100);
        
      }
      //

      let that = this;
      let dom = "<input class='td-input' id='td-input' type='text' value='' autofocus />";
      // 页面渲染好后点击触发
      that.$nextTick(function(){

        // 点击单元格
        $('#cell_result').find('table td').on('click', function(event) {

          if( that.$store.state.status.fileSearchVisible ){
            that.setFileSearchVisible(false);
          }
          
          if( that.$store.state.status.selectionBtnVisible ){
            that.setSelectionBtnVisible(false);
          }

          if( that.$store.state.status.fileDownloadVisible ){
            that.setFileDownloadVisible(false);
          }

          if( that.$store.state.status.qaVisible ){
            that.setQaVisible(false);
          }

          // console.log('nextTick0',  that.clickId);
          // 有活跃输入框
          if(that.clickId !== ''){
            return
          }

          // 高级功能模式
          if(that.advancedFunStatus == 2){
            return
          }

          if( _.indexOf(that.fileDownloadfileIds, that.activeFileId) !== -1 && window.getSelection().toString() == '' ){
            that.$message.warning(`文件导出中，请稍后操作！`);
          }

          // 当前文件正在导出，不能操作
          if( _.indexOf(that.fileDownloadfileIds, that.activeFileId) !== -1 ){
            return
          } 

          // 有复制内容
          if(window.getSelection().toString() !== ''){
            return
          }
          // console.log( 'cell_result table td click', event, that.isedit, event.currentTarget );

          // 校验
          if(event.currentTarget && !that.isedit ){
            // 有id的单元格
            if(event.currentTarget.id !== '' && event.currentTarget.id ){
              // 不是当前选中点击的单元格
              if( that.clickId !== event.currentTarget.id && that.clickId === '' ){
                that.selectionSwitchChange(event, false);
                that.clickId = event.currentTarget.id;
                that.oldDom = event.currentTarget.innerHTML;
                that.oldValue = event.currentTarget.innerText;
                that.newValue = event.currentTarget.innerText;
                $(this).empty();
                $(this).append(dom);

                $('.td-input').val(that.oldValue);
                $('.td-input').focus();
                $('.td-input')[0].focus();
                
                $('.td-input')[0].addEventListener("input",that.inputFun, true);
                $('.td-input')[0].addEventListener("blur",that.inputBlur, true);
                $('.td-input')[0].addEventListener("mouseup",that.inputUp, true);
                $('.td-input')[0].addEventListener("mousedown",that.inpuDown, true);
                console.log( 'td点击0', $('.td-input'), that.advancedFunStatus, that.clickId, that.oldDom, that.oldValue, that.newValue, that.fileEdit, );

                if(that.fileEdit !== 0){
                  // 换回来
                  $(this).empty();
                  $(this).append( that.oldDom );
                  $(this).find('span')[0].innerText = that.oldValue;

                  that.setFileEdit(0);
                  console.log( 'td点击1', );
                }
                //

              }
              //
            }
            //
          }
          //

        });
        //

      });
      //
    };
    //

    if( $("#cell_result") ){
      let that = this;
      // 点击单元格
      $("#cell_result").on('click', function(event) {

        // console.log('nextTick1',  that.clickId);
        // 有活跃输入框
        if(that.clickId !== ''){
          return
        }

        if(that.advancedFunStatus == 2){
          return
        }

        if( window.getSelection().toString() !== '' ){
          that.selectionSwitchChange(event, true);
        }
        else{
          that.selectionSwitchChange(event, false);
        }

      });
    };
    //

  },
  methods: {
    changeStyle () {
      this.$nextTick(function(){
        $('#cell_result').find('table td').addClass('cell-td');
        $('#cell_result').find('table p').addClass('cell-p')
        $('#cell_result').find('table tr:first-child').addClass('cell-th')
        let tdArray = $('#cell_result').find('table td');
        for (let i = 0; i < tdArray.length; i++) {
          // 给所有单元格绑定 id 用于鉴别点击所用
          $('#cell_result').find('table td')[i].id = `ocrTble-click-td-${i}`;

          let pArray = tdArray[i].children
          let text = ''
          let pTag = pArray[0]
          for (let j = 0; j < pArray.length; j++) {
            text += pArray[j].innerText
          }
          if(pTag){
            pTag.innerHTML = '<span class="s1">' + text + '</span>';
          }
          
          $('#cell_result').find('table td').eq(i).empty()
          $('#cell_result').find('table td').eq(i).append(pTag)
        }

      });
    },
    inputFun(event){
      event.stopPropagation(); // 冒泡
      // console.log('inputFun', event, event.path[0].value );
      this.newValue = event.path[0].value.length-20>this.oldValue.length ? (this.newValue!==''?this.newValue:this.oldValue) : event.path[0].value; // 修改内容值
      $('.td-input').val(this.newValue);
    },
    inputBlur(event){
      event.stopPropagation();

      let tdDom = $('.td-input').parent();
      // console.log( 'inputBlur0', event, tdDom, this.newValue, tdDom.find('span'), this.isedit );
      if(tdDom){
        tdDom.empty();
        tdDom.append( this.oldDom );
        if(tdDom.find('span').length){
          tdDom.find('span')[0].innerText = this.newValue;
        }
        else{
          // 暂无处理办法
        }
        this.selectionSwitchChange(event, false);
        this.selectionSwitchChange(event, true);
      }
      
      this.clickId = ''; // 清空当前点击

      if( $("#cell_result")[0] && this.newValue !== this.oldValue ){
        // console.log('inputBlur1', $("#cell_result")[0], );
        this.isedit = true;
        let str = $("#cell_result")[0].innerHTML;
        this.$http(this.$url.editOcrResult, {
          "id": this.doResultId,
          "mode": 2,
          "textLineId": '',
          "textLineSentValue": str,
          "type": '',
        }).then(res => {
          this.oldDom = ''; // 编辑之前的dom结构
          this.oldValue = ''; // 编辑之前的value值
          this.newValue = ''; // 编辑之后的value值
          this.tableHtmlS = str;

          setTimeout(() => {
            this.timeKey = (new Date()).valueOf();
            this.isedit = false;
          }, 500);

          if(res.state.ok == 1){
            this.$message.success(`修改成功！`);
          }
          else{
            this.$message.warning(`修改失败！`);
          }
        });
      }
      
    },
    inputUp(event){
      event.stopPropagation();
      // console.log( 'inputUp', event );
      if(window.getSelection().toString() == ''){
        this.selectionSwitchChange(event,false);
      }
    },
    inpuDown(event){
      event.stopPropagation();
      // console.log( 'inpuDown', event, $('#fileShow'), $('#folder-box'), $('#main-img') , event.path[0].value );
      if(event.path[0].value.length === 0){
        $('.td-input').focus();
        $('.td-input')[0].focus();
        return
      }

      if(event.button === 2 && window.getSelection().toString() !== ''){
        this.selectionSwitchChange(event, true);
        let fileWidth =  $('#folder-box')[0].clientWidth||0;
        let imgWidth = $('#fileShow')[0].clientWidth||0;
        let scrollTop = $('#main-img')[0].scrollTop||0;
        let scrollLeft = $('#main-img')[0].scrollLeft||0;
        let mouse = {top: `${event.clientY-140-10+scrollTop+20}px`, left: `${event.clientX-fileWidth-16-imgWidth-16-80+scrollLeft+60}px` };
        this.auxPositionChange(mouse);
      }
      else{
        this.selectionSwitchChange(event, false);
      }

    },
  },
  watch: {
    tableHtml (newVal) {
      if (newVal.indexOf('table') > -1) {
        this.tableHtmlS = newVal;
      }
    },
    tableHtmlS (newVal) {
      if (newVal.indexOf('table') > -1) {
        this.changeStyle();
      }
    },
    fileEdit (newVal){
      if( newVal === 3){
        console.log('table fileEdit', newVal, $("#cell_result").find('td').eq(0) );
        $("#cell_result").find('td').eq(0).click();
      }
    },
  },
  computed: {
    advancedFunStatus() {
      if(this.$store.state.status.advancedFunStatus === 2){
        this.selectionSwitchChange(event,false);
      }
      else{
        this.selectionSwitchChange(event, true);
      }
      return this.$store.state.status.advancedFunStatus;
    },
    activeFileId() {
      return this.$store.state.activeFile.id;
    },
    fileDownloadfileIds() {
      return this.$store.state.status.fileDownloadfileIds;
    },
    fileEdit() {
      return this.$store.state.status.fileEdit;
    },
  },
}
</script>

<style>
  .ocr-table-html {
    position: absolute;
    top: 0;
    padding: 20px;
    width: 100%;
  }
  #cell_result{
    position: relative;
  }
  #cell_result table {
    width: 100%;
    margin-bottom: 20px;
  }
  #cell_result .cell-td {
    border: 1px solid #ccc;
  }
  #cell_result .cell-p {
    text-indent: 0;
    padding: 10px;
    font-size: 16px !important;
    margin-bottom: 0;
  }
  #cell_result .cell-th {
    background-color: #fafafa;
  }
  #cell_result .s1 {
    color: black;
    word-break: break-all;
  }
  .td-input{
    border: 0px;
    border-bottom: 1px solid #03060f !important;
    width: 100%;
  }
  .td-input:hover,
  .td-input:focus {
    outline: none !important;
    -webkit-appearance: none !important;
  }
</style>
